package com.cy.metrics;

import com.codahale.metrics.*;
import com.cy.util.U;
import org.testng.annotations.Test;

import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

/**
 * https://metrics.dropwizard.io/3.1.0/
 *
 * @author yue.cao
 * @since 12-29-2020
 */
public class HistogramsDemo {


	// 不同的策略只会影响median值的计算方式 其他的不影响
	// 直方图可以看到数据的问题  爬坡式 等等

	@Test(description = "直方图 默认采取 指数衰减 new ExponentiallyDecayingReservoir()")
	public void testHistogram() throws InterruptedException {
		MetricRegistry registry = new MetricRegistry();

		ConsoleReporter reporter = ConsoleReporter
				.forRegistry(registry)
				.convertRatesTo(TimeUnit.MINUTES)
				.convertDurationsTo(TimeUnit.MINUTES).build();
		reporter.start(5, TimeUnit.SECONDS);

		Histogram histogram = registry.histogram("search-result");
		while (true) {
			histogram.update(ThreadLocalRandom.current().nextInt(100));
			U.sleepRandom();
		}
	}

	@Test(description = "直方图 UniformReservoir 他会统计你程序从开始到最终所有的数据" +
			" 缺点如果你最近 有类似活动 最近的数据发生了比较大幅度的改变 用这种方式可能就不能很好的体现了")
	public void testHistogram_UniformReservoir() {
		MetricRegistry registry = new MetricRegistry();

		ConsoleReporter reporter = ConsoleReporter
				.forRegistry(registry)
				.convertRatesTo(TimeUnit.MINUTES)
				.convertDurationsTo(TimeUnit.MINUTES).build();
		reporter.start(5, TimeUnit.SECONDS);

		Histogram histogram = new Histogram(new UniformReservoir());
		registry.register("UniformReservoir", histogram);
		while (true) {
			histogram.update(ThreadLocalRandom.current().nextInt(100));
			U.sleepRandom();
		}
	}

	@Test(description = "直方图 SlidingWindowReservoir 通过大小计算滑动窗口 计算 median")
	public void testHistogram_SlidingWindowReservoir() {
		MetricRegistry registry = new MetricRegistry();

		ConsoleReporter reporter = ConsoleReporter
				.forRegistry(registry)
				.convertRatesTo(TimeUnit.MINUTES)
				.convertDurationsTo(TimeUnit.MINUTES).build();
		reporter.start(5, TimeUnit.SECONDS);

		Histogram histogram = new Histogram(new SlidingWindowReservoir(50));
		registry.register("UniformReservoir", histogram);
		while (true) {
			histogram.update(ThreadLocalRandom.current().nextInt(100));
			U.sleepRandom();
		}
	}

	@Test(description = "直方图 SlidingTimeWindowReservoir 通过 时间作为滑动窗口 数据计算 median")
	public void testHistogram_SlidingTimeWindowReservoir() {
		MetricRegistry registry = new MetricRegistry();

		ConsoleReporter reporter = ConsoleReporter
				.forRegistry(registry)
				.convertRatesTo(TimeUnit.MINUTES)
				.convertDurationsTo(TimeUnit.MINUTES).build();
		reporter.start(5, TimeUnit.SECONDS);

		Histogram histogram = new Histogram(new SlidingTimeWindowReservoir(5, TimeUnit.SECONDS));
		registry.register("UniformReservoir", histogram);
		while (true) {
			histogram.update(ThreadLocalRandom.current().nextInt(100));
			U.sleepRandom();
		}
	}


}
